import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.util.*;
import java.util.zip.*;

/**
 * 从ep字段中提取AES密钥
 * 
 * 假设：ep解密后的256字节中包含32字节的AES密钥
 */
public class ExtractKeyFromEP {
    
    private static final String EP_ENCRYPTED = 
        "qt0AJsNLEfayUx7S15jLfmQvMOpW6JJ+jCoxeXxn676R2OiN6xpLIQWSYe8ETFUF4+AaGrVY1wMCdyUPVaHM0J+8m+q/PUFgbiP3N8xSKQc4lIzzZuckbybYiFuLbEhcblmy162S5B70UJxzB6grhIVpsG/h0uw+JPaS2yTPpPVCiN/SImdOw2g12cun6niAwRZSQktZikzzbjwkRoiO8ehrwlAFJircnT1/1zba2oaGXLc/yU6cM2vWgJdyyoXJF4Mo/5XNBTDT+8yr1hPC5MKHWcTBB/isrRTD5CczInLgXHl48KKz18GkpPM7MML1GHb4pIjfTvu8hv/SLLW0sg==";
    
    private static final String PRIVATE_KEY_PEM = 
        "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCz8JyumzBRR1njdxPzCFpqWXrAUBiC4ycTbTDdWdpZkciwiXU5s/OxF5i7l+Hvwc9Ggjph/PKo7PpWhxZpzyEGpd6yVN9jAjJOt23o2TesgK8L/DAMhdJL8gNxKAQumbGF+ebMbcS8jWLxvDAqpmnEW8VdCLEjF6uqOPtcDmIkBF83W6oaeu32DzTr/NS16sUGQKxlflo9qPOl7VtcIsbR52klKK4uIyY23tWCouiyG84c/Uit+PleD5EYUGEu3p7IAAG5uJNzeUd0UjZDhy6x7ue+kGgcCmCNQ4zSS/bQHMknalwqJUvUSxtIf8dq+/D78m7d4Zt9n9ZD27t4Z2jHAgMBAAECggEAAr15RVdrpvE1NzeLADpyVghCzEbr+KJI6AzTn6tMneyQZ8/QDy7kWSAI3WJ0uFf1Nhepl/BoKZZiQYsRFk9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CyqnFSUt8lsFlcUbJdK02TcMbd789pANnrKTTfFeOUehu5XReHng4DfV7f6boQmJPnZfwuR8qFwp7vwme235RTloktlkQu/2QFl2LmCv+/8Za43dEdFba9Ae6I1p+50zunyIjGTE6/9RT+g/zgagzgV/qDDSM5VF6E2Ic62W/KkpfSPMHAk5Jwg0LlsSMnFXYCynZoDZ5M8s62V15VaEII3s/6wPCu4lba/BxPanRtw60EVsvrJ7B0mnG+hcW8AGVeG1ZBIhgPH887/bY+05b0MnSkhjlrys8GKSaukVbtnrLJmjePt+LdLe6tH2NTwxjbHhJR028ZWaQKvdC5BD2hRflDMBPKL68D6YJ2bitqnKKdEqYHdCMXtOXh68XUqwfkoF3phQtYHyrqF4Wsgukf3/gAlt/yF0dXFTIUzoDTc34MEAaLFENVFDt4PUnYw2SRT8i/bhi3tcavu6Hnjs=";
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    
    private static void printBytes(byte[] bytes, String label) {
        System.out.println(label + " (" + bytes.length + " 字节):");
        System.out.println("  十六进制: " + bytesToHex(bytes));
        
        // 显示ASCII可打印字符
        StringBuilder ascii = new StringBuilder();
        for (byte b : bytes) {
            if (b >= 32 && b < 127) {
                ascii.append((char) b);
            } else {
                ascii.append('.');
            }
        }
        System.out.println("  ASCII: " + ascii.toString());
        System.out.println();
    }
    
    /**
     * 尝试使用ep中不同位置的32字节作为AES密钥
     */
    private static void tryKeysFromEP() {
        System.out.println("=".repeat(80));
        System.out.println("从ep字段中提取可能的AES密钥");
        System.out.println("=".repeat(80));
        
        try {
            // 1. RSA解密ep
            byte[] epBytes = Base64.getDecoder().decode(EP_ENCRYPTED);
            byte[] privateKeyBytes = Base64.getDecoder().decode(PRIVATE_KEY_PEM);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            
            Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
            rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] epDecrypted = rsaCipher.doFinal(epBytes);
            
            System.out.println("\n✅ ep解密成功（RSA/ECB/NoPadding）");
            printBytes(epDecrypted, "ep完整解密内容");
            
            // 2. 分析ep的结构
            System.out.println("\n" + "-".repeat(80));
            System.out.println("分析ep结构（256字节）:");
            System.out.println("-".repeat(80));
            
            // 显示不同位置
            System.out.println("字节0: " + String.format("0x%02x", epDecrypted[0]));
            System.out.println("字节1-32 (可能是密钥):"); 
            printBytes(Arrays.copyOfRange(epDecrypted, 1, 33), "  位置[1:33]");
            
            System.out.println("字节33-64:");
            printBytes(Arrays.copyOfRange(epDecrypted, 33, 65), "  位置[33:65]");
            
            System.out.println("最后32字节:");
            printBytes(Arrays.copyOfRange(epDecrypted, 224, 256), "  位置[224:256]");
            
            // 3. 尝试使用不同位置的32字节作为密钥
            System.out.println("\n" + "=".repeat(80));
            System.out.println("尝试使用ep中不同位置的32字节解密data");
            System.out.println("=".repeat(80));
            
            byte[] dataBytes = Base64.getDecoder().decode(DATA_ENCRYPTED);
            byte[] dataIv = Arrays.copyOf(dataBytes, 16);
            byte[] dataCiphertext = Arrays.copyOfRange(dataBytes, 16, dataBytes.length);
            
            // 尝试所有可能的32字节窗口
            for (int offset = 0; offset <= epDecrypted.length - 32; offset++) {
                byte[] possibleKey = Arrays.copyOfRange(epDecrypted, offset, offset + 32);
                
                try {
                    SecretKeySpec aesKeySpec = new SecretKeySpec(possibleKey, "AES");
                    IvParameterSpec ivSpec = new IvParameterSpec(dataIv);
                    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                    aesCipher.init(Cipher.DECRYPT_MODE, aesKeySpec, ivSpec);
                    byte[] decrypted = aesCipher.doFinal(dataCiphertext);
                    
                    // 尝试解压
                    try {
                        Inflater inflater = new Inflater(true);
                        inflater.setInput(decrypted);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        while (!inflater.finished()) {
                            int count = inflater.inflate(buffer);
                            baos.write(buffer, 0, count);
                        }
                        byte[] decompressed = baos.toByteArray();
                        String result = new String(decompressed, StandardCharsets.UTF_8);
                        
                        if (result.length() > 10 && result.contains("{")) {
                            System.out.println("\n🎉🎉🎉 找到正确的密钥！🎉🎉🎉");
                            System.out.println("=".repeat(80));
                            System.out.println("密钥位置: ep[" + offset + ":" + (offset+32) + "]");
                            System.out.println("密钥内容: " + bytesToHex(possibleKey));
                            System.out.println("=".repeat(80));
                            System.out.println("\n解密后的data内容:");
                            System.out.println(result);
                            System.out.println("\n=".repeat(80));
                            return;
                        }
                    } catch (Exception e) {
                        // 解压失败，继续尝试
                    }
                } catch (Exception e) {
                    // AES解密失败，继续尝试
                }
            }
            
            System.out.println("\n❌ 未能在ep中找到正确的AES密钥");
            System.out.println("可能密钥不在ep中，或者需要进一步处理");
            
        } catch (Exception e) {
            System.err.println("❌ 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 尝试对ep解密数据进行哈希处理
     */
    private static void tryHashedKeys() {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("尝试对ep数据进行哈希处理");
        System.out.println("=".repeat(80));
        
        try {
            // RSA解密ep
            byte[] epBytes = Base64.getDecoder().decode(EP_ENCRYPTED);
            byte[] privateKeyBytes = Base64.getDecoder().decode(PRIVATE_KEY_PEM);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            
            Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
            rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] epDecrypted = rsaCipher.doFinal(epBytes);
            
            byte[] dataBytes = Base64.getDecoder().decode(DATA_ENCRYPTED);
            byte[] dataIv = Arrays.copyOf(dataBytes, 16);
            byte[] dataCiphertext = Arrays.copyOfRange(dataBytes, 16, dataBytes.length);
            
            // 尝试不同的哈希算法
            MessageDigest[] digests = {
                MessageDigest.getInstance("SHA-256"),
                MessageDigest.getInstance("MD5"),
                MessageDigest.getInstance("SHA-1"),
            };
            
            String[] labels = {"SHA-256", "MD5", "SHA-1"};
            
            for (int i = 0; i < digests.length; i++) {
                // 对ep整体哈希
                byte[] hash1 = digests[i].digest(epDecrypted);
                if (hash1.length == 16) {
                    // MD5 -> 扩展到32字节
                    hash1 = Arrays.copyOf(hash1, 32);
                    System.arraycopy(hash1, 0, hash1, 16, 16);
                }
                
                tryKey(hash1, dataIv, dataCiphertext, labels[i] + "(完整ep)");
                
                // 对ep去掉第一个字节后哈希
                byte[] epWithoutFirst = Arrays.copyOfRange(epDecrypted, 1, epDecrypted.length);
                MessageDigest digest2 = MessageDigest.getInstance(digests[i].getAlgorithm());
                byte[] hash2 = digest2.digest(epWithoutFirst);
                if (hash2.length == 16) {
                    hash2 = Arrays.copyOf(hash2, 32);
                    System.arraycopy(hash2, 0, hash2, 16, 16);
                }
                
                tryKey(hash2, dataIv, dataCiphertext, labels[i] + "(ep[1:])");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void tryKey(byte[] key, byte[] iv, byte[] ciphertext, String label) {
        if (key.length != 32) {
            return;
        }
        
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decrypted = cipher.doFinal(ciphertext);
            
            // 解压
            Inflater inflater = new Inflater(true);
            inflater.setInput(decrypted);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                baos.write(buffer, 0, count);
            }
            byte[] decompressed = baos.toByteArray();
            String result = new String(decompressed, StandardCharsets.UTF_8);
            
            if (result.length() > 10 && result.contains("{")) {
                System.out.println("\n🎉🎉🎉 找到正确的密钥！🎉🎉🎉");
                System.out.println("=".repeat(80));
                System.out.println("密钥来源: " + label);
                System.out.println("密钥内容: " + bytesToHex(key));
                System.out.println("=".repeat(80));
                System.out.println("\n解密后的data内容:");
                System.out.println(result);
                System.out.println("\n=".repeat(80));
                System.exit(0);
            }
        } catch (Exception e) {
            // 失败，继续
        }
    }
    
    public static void main(String[] args) {
        System.out.println("=".repeat(80));
        System.out.println("从EP字段提取AES密钥");
        System.out.println("=".repeat(80));
        
        // 方法1: 直接尝试ep中的32字节片段
        tryKeysFromEP();
        
        // 方法2: 尝试对ep进行哈希处理
        tryHashedKeys();
        
        System.out.println("\n分析完成");
    }
}



